package com.yjt.sousou.create;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;
import com.permissionx.guolindev.PermissionX;
import com.yjt.sousou.Api;
import com.yjt.sousou.Constant;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseCreateOrderActivity;
import com.yjt.sousou.camera.preview.ImagePreviewActivity;
import com.yjt.sousou.create.entity.Department;
import com.yjt.sousou.create.entity.Device;
import com.yjt.sousou.create.entity.FaultType;
import com.yjt.sousou.create.entity.FaultTypeSelect;
import com.yjt.sousou.create.entity.Finish;
import com.yjt.sousou.create.entity.ImageItem;
import com.yjt.sousou.create.entity.Location;
import com.yjt.sousou.create.entity.UpLoadFile;
import com.yjt.sousou.detail.CommonPop;
import com.yjt.sousou.detail.entity.FilterBean;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.BitCompressUtil;
import com.yjt.sousou.utils.GetTimeUtil;
import com.yjt.sousou.utils.HDPreference;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.internal.utils.PathUtils;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yjt.sousou.camera.preview.ImagePreviewActivity.CURRENT_POSITION;
import static com.yjt.sousou.camera.preview.ImagePreviewActivity.IMAGE_DATA;


/**
 * 作者：83734
 * 时间：2018/11/23
 * 描述：新建工单
 */
public class CreateNewOrderActivity extends BaseCreateOrderActivity {
    @BindView(R.id.rl_pic)
    RecyclerView mRlPic;
    @BindView(R.id.rl_main)
    RelativeLayout mRlMain;
    @BindView(R.id.tv_mic)
    TextView mTvMic;
    @BindView(R.id.tv_info)
    TextView mTvInfo;
    @BindView(R.id.mic_icon)
    ImageView mMicIcn;
    @BindView(R.id.time_display)
    Chronometer mChronometer;//录音定时
    @BindView(R.id.audio_layout)
    RelativeLayout mAudioLayout;
    @BindView(R.id.scrollview)
    ScrollView mScrollView;
    @BindView(R.id.iv_play_audio)
    ImageView mIvPlayAudio;
    @BindView(R.id.tv_urgency)
    TextView mTvUrgency;
    @BindView(R.id.tv_common)
    TextView mTvCommon;
    @BindView(R.id.tv_daily)
    TextView mTvDaily;
    @BindView(R.id.tv_department)
    TextView mTvDepartment;
    @BindView(R.id.tv_select_place)
    TextView mTvPlace;
    @BindView(R.id.tv_device)
    TextView mTvDevice;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_reason)
    EditText mEtReason;
    @BindView(R.id.et_cause)
    EditText mEtCause;
    @BindView(R.id.rv_fault_type)
    RecyclerView mRvFaultType;

    private List<FaultTypeSelect> mFaultTypes = new ArrayList<>();
    private FaultTypeAdapter mFaultTypeAdapter;
    private List<FilterBean> mDepartments = new ArrayList<>();
    private List<FilterBean> mDevices = new ArrayList<>();
    private List<Location.DataBean> mAreas = new ArrayList<>();
    private List<Location.DataBean.DidianListsBean> mPlaces = new ArrayList<>();
    private List<FaultType.DataBean> mFaultTypeLeft = new ArrayList<>();
    private List<FaultType.DataBean.GzlxListsBean> mFaultTypeRight = new ArrayList<>();
    private List<FaultType.DataBean.GzlxListsBean> mFaultSearchData = new ArrayList<>();
    private String areaName = "";
    private String placeName = "";
    private String departmentId = "";
    private String areaId = "";
    private String placeId = "";
    private String deviceId = "";
    private String faultLeftId = "";
    private String faultRightId = "1";
    private String faultName = "";
    private String faultNameRight = "";
    private int grade = 3;//等级
    private String timestamp = "";
    private String fileIds = "";
    private List<TextView> mTextView = new ArrayList<>();
    private String permission;
    @Override
    protected Object setContentLayout() {
        return R.layout.activity_create_new_order;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        mUserId =  HDPreference.getUserId(LoginTag.USER_ID.name());
        initData();
        initRecycleView();
        getWindow().getDecorView().post(new Runnable() {
           @Override
           public void run() {
               setConst();
           }
       });
    }

    private void setConst() {
        initAudio();
        PermissionX.init(this)
                .permissions(Manifest.permission.RECORD_AUDIO,Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> ToastUtils.showLong("即将申请的权限是程序必须依赖的权限"))
                .onForwardToSettings((scope, deniedList) -> ToastUtils.showLong("您需要去应用程序设置当中手动开启权限"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                    } else {
                        ToastUtils.showLong("录音权限被禁止，无法录音");
                    }
                });
        mTvMic.setOnTouchListener(touchListener);
        mChronometer.setOnChronometerTickListener(tickListener);
        String phone =  HDPreference.getUserId(LoginTag.PHONE.name());
        mEtPhone.setText(phone);
        String username = HDPreference.getUserId(LoginTag.USER_NAME.name());
        mEtName.setText(username);
        String departmentName = HDPreference.getUserId(LoginTag.DEPARTMENT.name());
        mTvDepartment.setText(departmentName);
        departmentId = HDPreference.getUserId(LoginTag.DEPARTMENT_ID.name());
        permission =  HDPreference.getUserId(LoginTag.PERMISSION.name());
        LogUtils.i(permission);
        String currentTime = GetTimeUtil.long2StringHHmm2(System.currentTimeMillis()/1000);
        mTvTime.setText(currentTime);
        mTextView.add(mTvDaily);
        mTextView.add(mTvCommon);
        mTextView.add(mTvUrgency);
    }

    private void initData() {
        OkGo.<Department>get(Api.get().getDepartment())
                .tag(this)
                .execute(new DialogCallback<Department>(Department.class,this) {
                    @Override
                    public void onSuccess(Response<Department> response) {
                        Department body = response.body();
                        for (Department.DataBean data : body.getData()) {
                            mDepartments.add(new FilterBean(data.getId(),data.getBumen()));
                        }
                    }
                });
        OkGo.<Location>get(Api.get().getLocation())
                .tag(this)
                .params("user_id",mUserId)
                .execute(new DialogCallback<Location>(Location.class,this) {
                    @Override
                    public void onSuccess(Response<Location> response) {
                        Location location = response.body();
                        if(location!=null&&location.getData().size()!=0){
                            mAreas.addAll(location.getData());
                        }
                    }
                });
        OkGo.<FaultType>get(Api.get().getFaultType())
                .tag(this)
                .execute(new DialogCallback<FaultType>(FaultType.class,this) {
                    @Override
                    public void onSuccess(Response<FaultType> response) {
                        FaultType faultType = response.body();
                        if(faultType!=null&&faultType.getData().size()!=0){
                            mFaultTypeLeft.addAll(faultType.getData());
                        }
                    }
                });
    }

    @OnClick({R.id.et_name,R.id.iv_play_audio,R.id.tv_urgency,R.id.tv_common,R.id.tv_daily,R.id.tv_device,R.id.tv_time,R.id.tv_select_place,
            R.id.tv_department,R.id.tv_fault_type,R.id.tv_submit})
    void onClick(View view){
        switch (view.getId()){
            case R.id.et_name:
                mEtName.setCursorVisible(true);
                break;
            case R.id.iv_play_audio:
                AnimationDrawable animationDrawable = (AnimationDrawable) mIvPlayAudio.getDrawable();
                animationDrawable.start();
                playAudio();
                break;
            case R.id.tv_daily:
                grade = 3;
                setState(mTextView,0);
                break;
            case R.id.tv_common:
                grade = 2;
                setState(mTextView,1);
                break;
            case R.id.tv_urgency:
                grade = 1;
                setState(mTextView,2);
                break;
            case R.id.tv_department:
                if(permission.contains("119")){
                    CommonPop departmentPop = new CommonPop(this, mDepartments, new CommonPop.ResultListener() {
                        @Override
                        public void res(String id, String name) {
                            departmentId = id;
                            mTvDepartment.setText(name);
                            LogUtils.i("departmentid",departmentId);
                        }
                        @Override
                        public void dismiss() {
                            makeWindowLight();
                        }
                    });
                    departmentPop.show(mRlMain);
                    makeWindowDark();
                }else {
                    showToast("您没有更改部门的权限");
                }

                break;
            case R.id.tv_device:
                if(TextUtils.isEmpty(placeId)&&TextUtils.isEmpty(areaId)){
                    showToast("请先选择位置");
                }else {
                    CommonPop placePop = new CommonPop(this, mDevices, new CommonPop.ResultListener() {
                        @Override
                        public void res(String id, String name) {
                            deviceId = id;
                            mTvDevice.setText(name);
                            LogUtils.i("deviceId",deviceId);
                        }
                        @Override
                        public void dismiss() {
                            makeWindowLight();
                        }
                    });
                    placePop.show(mRlMain);
                    makeWindowDark();
                }
                break;
            case R.id.tv_time:
                showTime(mRlMain);
                makeWindowDark();
                break;
            case R.id.tv_select_place:
                showPlacePop();
                makeWindowDark();
                break;
            case R.id.tv_fault_type:
               showFaultTypePop();
               makeWindowDark();
                break;
            case R.id.tv_submit:
//                LogUtils.i(getFaultTypeJson());
                phone = mEtPhone.getText()==null?"":mEtPhone.getText().toString();
                if(TextUtils.isEmpty(phone)){
                    showToast("请填写回访电话");
                    return;
                }
                reason = mEtReason.getText()==null?"":mEtReason.getText().toString();
                if(TextUtils.isEmpty(reason)){
                    showToast("请填写原因");
                    return;
                }
                cause = mEtCause.getText()==null?"":mEtCause.getText().toString();
//                if(TextUtils.isEmpty(cause)){
//                    showToast("请填写备注");
//                    return;
//                }
                if(!TextUtils.isEmpty(mAudioPath)||mImgData.size()>1){
                    uploadFile();
                }else {
                    submit(reason,phone,cause);
                }
                break;
                default:
        }
    }
    private String phone = "";
    private String reason = "";
    private String cause = "";
    private String getFaultTypeJson() {
        Gson gson = new Gson();
        String s = gson.toJson(mFaultTypes);
        return s==null?"":s;
    }

    private void submit(String reason,String phone,String cause) {
        String name = mEtName.getText()==null?"":mEtName.getText().toString();

        String json = getFaultTypeJson();
        OkGo.<Finish>post(Api.get().getCreateNewOrder())
                .tag(this)
                .params("user_name",name)
                .params("user_id",mUserId)
                .params("bumen",departmentId)
                .params("quyu",areaId)
                .params("yuanyin",reason)
                .params("huifangdh",phone)
                .params("rlevel",grade)
                .params("beizhu",cause)
                .params("didian",placeId)
                .params("appointment_time",timestamp)
                .params("faulttype_info",json)
                .params("gz_file_ids",fileIds)
                .execute(new DialogCallback<Finish>(Finish.class,this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish finish = response.body();
                        if(finish.getReturncode().equals("0")){
                            showToast("提交工单成功");
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            showToast("提交工单失败");
                        }
                    }
                });
    }
    private void uploadFile(){
        ArrayList<File> files = new ArrayList<>();
        if(!TextUtils.isEmpty(mAudioPath)){
            files.add(new File(mAudioPath));
        }
        ArrayList<ImageItem> images = new ArrayList<>(mImgData);
        images.remove(images.size()-1);
        for (ImageItem imageItem: images) {
            if(!imageItem.isVideo()){
                Bitmap bitmap = BitCompressUtil.getSmallBitmap(imageItem.getPath());
                File file = new File(Constant.BXT_IMAGE_COMPRESS);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File imageFile = new File(file, String.valueOf(System.currentTimeMillis()) + ".jpg");
                BitCompressUtil.compressBmpToFile(bitmap, imageFile);
                files.add(imageFile);
            }else {
                files.add(new File(imageItem.getPath()));
            }
        }
        PostRequest<UpLoadFile> request = OkGo.<UpLoadFile>post(Api.get().getFile())
                .tag(this);
        for (int i = 0; i < files.size(); i++) {
            request.params("file_imgs"+i,files.get(i));
        }
        request
                .execute(new DialogCallback<UpLoadFile>(UpLoadFile.class,this) {
                    @Override
                    public void onStart(Request<UpLoadFile, ? extends Request> request) {
                        super.onStart(request);
                        showToast("正在上传文件");
                    }

                    @Override
                    public void onSuccess(Response<UpLoadFile> response) {
                            UpLoadFile loadFile = response.body();
                            String resCode = loadFile.getReturncode();
                            if(resCode.equals("0")){
                                fileIds = loadFile.getFile_ids();
                                LogUtils.i(fileIds);
//                                showToast("上传完成");
                                submit(reason,phone,cause);
                            }else {
                                showToast("上传文件失败");
                            }
                    }
                    @Override
                    public void onError(Response<UpLoadFile> response) {
                        super.onError(response);
                        showToast("上传文件错误："+response.message());
                    }
                });
    }

    @Override
    protected void setTime(String time) {
        mTvTime.setText(time);
        try {
            timestamp = GetTimeUtil.ymdhm2Timestamp2(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void initRecycleView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRlPic.setLayoutManager(manager);
        final Uri imageUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" +R.mipmap.add_photo);
        mImgData.add(new ImageItem(imageUri,false,""));
        mPicAdapter= new PicRecycleAdapter(R.layout.item_select_pic,mImgData);
        mRlPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(position == mImgData.size()-1){
                    showPicPop(mRlMain);
                    makeWindowDark();
                }else {
                    ArrayList<ImageItem> images = new ArrayList<>(mImgData);
                    images.remove(images.size()-1);
                    Intent intent = new Intent(getApplicationContext(), ImagePreviewActivity.class);
                    intent.putExtra(CURRENT_POSITION,position);
                    intent.putExtra(IMAGE_DATA,images);
                    startActivity(intent);
                }
            }
        });
        LinearLayoutManager faultTypeManager = new LinearLayoutManager(this);
        mRvFaultType.setLayoutManager(faultTypeManager);
        mFaultTypeAdapter = new FaultTypeAdapter(R.layout.item_fault_type,mFaultTypes);
        mRvFaultType.setAdapter(mFaultTypeAdapter);
    }


    //选择故障类型
    private void showFaultTypePop(){
        mFaultSearchData.clear();
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_place,null);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvConfirm = view.findViewById(R.id.tv_confirm);
        EditText etSearch = view.findViewById(R.id.et_search);
        LinearLayout llSelect = view.findViewById(R.id.ll_select);
        etSearch.setVisibility(View.VISIBLE);
        RecyclerView rvLeft = view.findViewById(R.id.rl_place_1);
        LinearLayoutManager managerLeft = new LinearLayoutManager(this);
        managerLeft.setOrientation(LinearLayoutManager.VERTICAL);
        rvLeft.setLayoutManager(managerLeft);
        RecyclerView rvRight = view.findViewById(R.id.rl_place_2);
        LinearLayoutManager managerRight = new LinearLayoutManager(this);
        managerRight.setOrientation(LinearLayoutManager.VERTICAL);
        rvRight.setLayoutManager(managerRight);
        RecyclerView rvSearch = view.findViewById(R.id.rv_search);
        LinearLayoutManager managerSearch = new LinearLayoutManager(this);
        managerSearch.setOrientation(LinearLayoutManager.VERTICAL);
        rvSearch.setLayoutManager(managerSearch);
        final BaseQuickAdapter leftAdapter = new BaseQuickAdapter<FaultType.DataBean,BaseViewHolder>(R.layout.item_my_pop_list,mFaultTypeLeft) {
            @Override
            protected void convert(BaseViewHolder helper, FaultType.DataBean item) {
                helper.setText(R.id.tv_name,item.getGzlx_type());
                if(item.isClicked()){
                    helper.setTextColor(R.id.tv_name, ContextCompat.getColor(getApplicationContext(),R.color.text_color));
                    helper.setBackgroundRes(R.id.rl_item,R.color.gray);
                }else {
                    helper.setTextColor(R.id.tv_name,ContextCompat.getColor(getApplicationContext(),R.color.black));
                    helper.setBackgroundRes(R.id.rl_item,R.color.white);
                }
            }
        };
        final SelectFaultTypeAdapter rightAdapter = new SelectFaultTypeAdapter(R.layout.item_my_pop_list,mFaultTypeRight);
        leftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<FaultType.DataBean> data = leftAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                mFaultTypeRight.clear();
                List<FaultType.DataBean.GzlxListsBean> gzlxLists = data.get(position).getGzlx_lists();
                for (FaultType.DataBean.GzlxListsBean gzlxList : gzlxLists) {
                    gzlxList.setClicked(false);
                }
                mFaultTypeRight.addAll(gzlxLists);
                faultNameRight = "";
                faultRightId = "";
                faultLeftId = data.get(position).getId();
                faultName = data.get(position).getGzlx_type();
                rightAdapter.notifyDataSetChanged();
                leftAdapter.notifyDataSetChanged();
            }
        });
        rvLeft.setAdapter(leftAdapter);
        rightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<FaultType.DataBean.GzlxListsBean> data = rightAdapter.getData();
                for (int i = 0; i <data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                faultRightId = data.get(position).getGzlx_id();
                faultNameRight = data.get(position).getGzlx_name();
                rightAdapter.notifyDataSetChanged();
            }
        });
        rvRight.setAdapter(rightAdapter);
        final SelectFaultTypeAdapter searchAdapter = new SelectFaultTypeAdapter(R.layout.item_my_pop_list,mFaultSearchData);
        rvSearch.setAdapter(searchAdapter);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!TextUtils.isEmpty(s.toString())){
                    getCustomerList(s.toString(),searchAdapter);
                    llSelect.setVisibility(View.GONE);
                    rvSearch.setVisibility(View.VISIBLE);
                }else {
                    llSelect.setVisibility(View.VISIBLE);
                    rvSearch.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });
        searchAdapter.setOnItemClickListener((adapter, view1, position) -> {
            List<FaultType.DataBean.GzlxListsBean> data = searchAdapter.getData();
            for (int i = 0; i <data.size(); i++) {
                data.get(i).setClicked(position == i);
            }
            faultLeftId = data.get(position).getGzlx_type_id();
            faultRightId = data.get(position).getGzlx_id();
            faultNameRight = data.get(position).getGzlx_name();
            faultName = data.get(position).getGzlx_type_name();
            searchAdapter.notifyDataSetChanged();
        });
        setPop(view,1);
        tvCancel .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFaultTypes.add(new FaultTypeSelect(faultRightId,faultLeftId,
                        "".equals(faultNameRight)?faultName:faultName+"-"+faultNameRight,String.valueOf(1)));
                mFaultTypeAdapter.notifyDataSetChanged();
                mPop.dismiss();
            }
        });
    }

    private void clearClick(){
        for (FaultType.DataBean dataBean : mFaultTypeLeft) {
            dataBean.setClicked(false);
            if(dataBean.getGzlx_lists()!=null&&!dataBean.getGzlx_lists().isEmpty()){
                for (FaultType.DataBean.GzlxListsBean gzlxList : dataBean.getGzlx_lists()) {
                    gzlxList.setClicked(false);
                }
            }
        }
    }

    /**
     * 搜索故障类型
     * @param searchName
     */
    private void getCustomerList(String searchName,BaseQuickAdapter adapter) {
        mFaultSearchData.clear();
        traversalAllType(mFaultTypeLeft,searchName);
        if(mFaultSearchData.isEmpty()){
            showToast("没有搜索到数据");
            mFaultSearchData.clear();
            adapter.setNewData(mFaultSearchData);
        }else {
            adapter.setNewData(mFaultSearchData);
        }
    }

    private void traversalAllType(List<FaultType.DataBean> list,String searchName){
        for (FaultType.DataBean outItem : list) {
            for (FaultType.DataBean.GzlxListsBean item : outItem.getGzlx_lists()) {
                if(item.getGzlx_name().contains(searchName)){
                    item.setClicked(false);
                    mFaultSearchData.add(item);
                }
            }
        }
    }


    //选择位置
    private void showPlacePop(){
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_place,null);
        TextView tv_cancel= view.findViewById(R.id.tv_cancel);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        RecyclerView rvLeft = view.findViewById(R.id.rl_place_1);
        LinearLayoutManager managerL = new LinearLayoutManager(this);
        managerL.setOrientation(LinearLayoutManager.VERTICAL);
        rvLeft.setLayoutManager(managerL);
        RecyclerView rvRight = view.findViewById(R.id.rl_place_2);
        LinearLayoutManager managerR = new LinearLayoutManager(this);
        managerR.setOrientation(LinearLayoutManager.VERTICAL);
        rvRight.setLayoutManager(managerR);
        final BaseQuickAdapter leftAdapter = new BaseQuickAdapter<Location.DataBean,BaseViewHolder>(R.layout.item_my_pop_list,mAreas) {
            @Override
            protected void convert(BaseViewHolder helper, Location.DataBean item) {
                helper.setText(R.id.tv_name,item.getQuyu());
                if(item.isClicked()){
                    helper.setTextColor(R.id.tv_name,ContextCompat.getColor(getApplicationContext(),R.color.text_color));
                    helper.setBackgroundRes(R.id.rl_item,R.color.gray);
                }else {
                    helper.setTextColor(R.id.tv_name,ContextCompat.getColor(getApplicationContext(),R.color.black));
                    helper.setBackgroundRes(R.id.rl_item,R.color.white);
                }
            }
        };
        final BaseQuickAdapter rightAdapter =new BaseQuickAdapter<Location.DataBean.DidianListsBean,BaseViewHolder>(R.layout.item_my_pop_list,mPlaces) {
            @Override
            protected void convert(BaseViewHolder helper, Location.DataBean.DidianListsBean item) {
                helper.setText(R.id.tv_name,item.getDidian_name());
                if(item.isClicked()){
                    helper.setTextColor(R.id.tv_name,ContextCompat.getColor(getApplicationContext(),R.color.text_color));
                    helper.setBackgroundRes(R.id.rl_item,R.color.gray);
                }else {
                    helper.setTextColor(R.id.tv_name,ContextCompat.getColor(getApplicationContext(),R.color.black));
                    helper.setBackgroundRes(R.id.rl_item,R.color.white);
                }
            }
        };
        leftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<Location.DataBean> data = leftAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                mPlaces.clear();
                mPlaces.addAll(data.get(position).getDidian_lists());
                placeId = "";
                placeName = "";
                areaId = data.get(position).getId();
                rightAdapter.notifyDataSetChanged();
                leftAdapter.notifyDataSetChanged();
                areaName = data.get(position).getQuyu();
            }
        });
        rvLeft.setAdapter(leftAdapter);

        rightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<Location.DataBean.DidianListsBean> data = rightAdapter.getData();
                for (int i = 0; i <data.size(); i++) {
                    data.get(i).setClicked(position == i);
                }
                placeId = data.get(position).getDidian_id();
                rightAdapter.notifyDataSetChanged();
                placeName = data.get(position).getDidian_name();
                LogUtils.i("placeId",placeId);
            }
        });
        rvRight.setAdapter(rightAdapter);

        setPop(view,1);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvPlace.setText(placeName.equals("")?areaName:areaName+"-"+placeName);
                getDevice();
                mPop.dismiss();
            }
        });
    }

    private void getDevice() {
        OkGo.<Device>get(Api.get().getDevice())
                .tag(this)
                .params("didian_id",placeId)
                .execute(new DialogCallback<Device>(Device.class,this) {
                    @Override
                    public void onSuccess(Response<Device> response) {
                        Device device = response.body();
                        if(device!=null&&device.getData()!=null&&device.getData().size()!=0){
                            List<Device.DataBean> data = device.getData();
                            for (Device.DataBean entity : data) {
                                mDevices.add(new FilterBean(entity.getId(),entity.getSb_name()));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<Device> response) {
//                        super.onError(response);
//                        showToast("该位置下没有设备");
                    }
                });
    }


    private void setPop(View view ,int heightType){
        mPop = new PopupWindow(view, 5 * mScreenWidth / 6,heightType==1?2*mScreenWidth/3:ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
                clearClick();
            }
        });
        mPop.showAtLocation(mRlMain, Gravity.CENTER, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CreateConst.REQUEST_CODE_CHOOSE_PIC && resultCode == RESULT_OK) {
            if (data!=null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    if(!mImgData.contains(uri)){
                        mImgData.add(0,new ImageItem(uri,false,PathUtils.getPath(this,uri)));
                    }
                }
                mPicAdapter.notifyDataSetChanged();
            }
            LogUtils.i("OnActivityResult ", String.valueOf(Matisse.obtainOriginalState(data)));
        }
        if (requestCode == CreateConst.REQUEST_CODE_TAKE_PIC && resultCode == 101) {
            String path = data.getStringExtra("path");
            LogUtils.i("CJT", "picture"+path);
            Uri picUri = getImageUri(path);
            LogUtils.i("CJT", "pictureuri"+picUri);
            if(!mImgData.contains(picUri)){
                mImgData.add(0,new ImageItem(picUri,false,path));
            }
            mPicAdapter.notifyDataSetChanged();
        }
        if (requestCode == CreateConst.REQUEST_CODE_TAKE_PIC && resultCode == 102) {
            String path = data.getStringExtra("path");
            String videoPath = data.getStringExtra("video_path");
            LogUtils.i("CJT", "video"+path);
            Uri imgUri = getImageUri(path);
            Uri videoUri = getImageUri(videoPath);
            if(!mImgData.contains(imgUri)){
                mImgData.add(0,new ImageItem(imgUri,true,videoUri,videoPath));
            }
            mPicAdapter.notifyDataSetChanged();
        }

    }

    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mScrollView.requestDisallowInterceptTouchEvent(true);
            boolean ret = false;
            float downY = 0;
            int action = event.getAction();
            switch (v.getId()) {
                case R.id.tv_mic:
                    switch (action) {
                        case MotionEvent.ACTION_DOWN:
                            if(hasPermission(getApplication(),Manifest.permission.RECORD_AUDIO)){
                                startAnim(true);
                                mMediaUtils.record();
                                ret = true;
                            }else {
                                showToast("缺少录音权限,请查看手机设置");
                                return false;
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            stopAnim();
                            if (isCancel) {
                                isCancel = false;
                                mMediaUtils.stopRecordUnSave();
                                showToast("取消保存");
                            } else {
                                int duration = getDuration(mChronometer.getText().toString());
                                switch (duration) {
                                    case -1:
                                        break;
                                    case -2:
                                        mMediaUtils.stopRecordUnSave();
                                        showToast("时间太短");
                                        break;
                                    default:
                                        mMediaUtils.stopRecordSave();
                                        String path = mMediaUtils.getTargetFilePath();
                                        mAudioPath = path;
                                        mIvPlayAudio.setVisibility(View.VISIBLE);
//                                        showToast("文件保存至：" + path);
                                        break;
                                }
                            }
                            break;
                        case MotionEvent.ACTION_MOVE:
                            float currentY = event.getY();
                            if (downY - currentY > 10) {
                                moveAnim();
                                isCancel = true;
                            } else {
                                isCancel = false;
                                startAnim(false);
                            }
                            break;
                    }
                    break;
            }
            return ret;
        }
    };

    Chronometer.OnChronometerTickListener tickListener = new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer chronometer) {
            if (SystemClock.elapsedRealtime() - chronometer.getBase() > 60 * 1000) {
                stopAnim();
                mMediaUtils.stopRecordSave();
                showToast("录音超时");
                String path = mMediaUtils.getTargetFilePath();
                mAudioPath = path;
//                showToast("文件保存至：" + path);
            }
        }
    };



    private void startAnim(boolean isStart){
        mAudioLayout.setVisibility(View.VISIBLE);
        mTvInfo.setText("上滑取消");
        mTvMic.setBackgroundResource(R.color.text_color);
        mMicIcn.setBackground(null);
        mMicIcn.setBackground(getResources().getDrawable(R.mipmap.ic_mic_white_24dp));
        if (isStart){
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mChronometer.setFormat("%S");
            mChronometer.start();
        }
    }

    private void stopAnim(){
        mAudioLayout.setVisibility(View.GONE);
        mTvMic.setBackgroundResource(R.color.blue_bg);
        mChronometer.stop();
    }

    private void moveAnim(){
        mTvInfo.setText("松手取消");
        mMicIcn.setBackground(null);
        mMicIcn.setBackground(getResources().getDrawable(R.mipmap.ic_undo_black_24dp));
    }

}
